package com.suse.service.community.quartz;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.util.date.DateUtil;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.constant.PostConstant;
import com.suse.service.community.entity.DiscussPost;
import com.suse.service.community.service.DiscussPostService;
import com.suse.service.community.service.ElasticsearchService;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * <p>
 * 帖子分数刷新任务
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-07 13:35
 */
@Slf4j
public class PostScoreRefreshJob implements Job {

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    @Resource
    private DiscussPostService postService;

    @Resource
    private LikeService likeService;

    @Resource
    private ElasticsearchService elasticsearchService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        String needRefreshScorePostsKey = RedisUtil.getNeedRefreshScorePostsKey();
        BoundSetOperations<Object, Object> boundSetOps = redisTemplate.boundSetOps(needRefreshScorePostsKey);
        Long size = boundSetOps.size();
        if (ObjectUtil.isNull(size) || size == 0) {
            log.info("[任务取消] 没有需要刷新分数的帖子");
            return;
        }
        log.info("[任务开始] 正在刷新帖子分数...");
        while(size != null && size > 0) {
            this.refreshPostScore((Integer) boundSetOps.pop());
            size = boundSetOps.size();
        }
        log.info("[任务结束] 帖子分数刷新完毕！");
    }

    private void refreshPostScore(Integer postId) {
        // 通过ID获取帖子信息
        DiscussPost post = postService.getById(postId);
        if (ObjectUtil.isNull(post)) {
            log.warn("id={}的帖子不存在,该帖子可能已经被删除",postId);
        }
        // 是否精华
        boolean isEssence = post.getStatus() == PostConstant.ESSENCE;
        // 评论数
        int commentCount = post.getCommentCount();
        // 点赞数量
        long likeCount = likeService.getEntityLikeCount(EntityTypeConstant.POST,postId);
        // 计算权重
        double w = (isEssence ? 75 : 0) + commentCount * 10 + likeCount * 2;
        // 计算分数
        Date createTime = post.getCreateTime();
        Date now = DateUtil.now();
        double score = Math.log10(Math.max(w,1)) + DateUtil.until(createTime,now, ChronoUnit.DAYS);
        // 更新分数
        postService.updateScore(postId,score);
        // 同步 Elasticsearch 数据
        post.setScore(score);
        elasticsearchService.saveDiscussPost(post);
    }

}
